package org.dream.ui.chart.impl;

import java.awt.Graphics;
import java.util.Map;

import org.dream.service.StockDayService;
import org.dream.service.StockDayServiceImpl;
import org.dream.ui.chart.XAxis;
import org.dream.ui.chart.XAxisModel;

/**
 * X轴实现
 * 
 * @author qiuriyuchen E-mail:panpan_001@126.com
 */
public class XAxisImpl extends AxisImpl implements XAxis {

	private StockDayService stockDayService = new StockDayServiceImpl();

	private XAxisModel xAxisModel;

	public XAxisImpl(int minValue, int maxValue, Map<Integer, String> tickViews) {
		xAxisModel = new XAxisModelImpl(minValue, maxValue, tickViews);

	}

	public XAxisModel getXAxisModel() {
		return xAxisModel;
	}

	public void draw(Graphics g) {
		drawLine(g);
		drawTick(g);

	}

	private void drawLine(Graphics g) {
		/* 设置轴线颜色 */
		g.setColor(axisColor);
		/* 绘制横轴 */
		g.drawLine(xAxisModel.getPixelXLeft(), xAxisModel.getPixelYButtom(), xAxisModel.getPixelXRight(),
				xAxisModel.getPixelYButtom());
	}

	/**
	 * 画刻度线
	 */
	private void drawTick(Graphics g) {
		// 刻度间距，原点刻度是不用的，所以要多算一个,但画的时候左边用半个，右边用半个，后加入getRangeValue，其实没多算，应该计数分成几个
		for (int i = xAxisModel.getMinValue(); i <= xAxisModel.getMaxValue(); i++) {
			String day = xAxisModel.getTickDay(i);
			try {
				// 如果只显示月，如果不是第一个月第一天就不显
				if (xAxisModel.isOnlyDrawMonth() && !stockDayService.isMonthFirstOpenDay(day)) {
					continue;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			// 设置刻度值,要减去半个
			int tickX = xAxisModel.translateValueToPx(i);
			if (xAxisModel.isDrawGrid()) {
				/* 如果drawGrid属性为true,用gridColor绘制网格线 */
				g.setColor(gridColor);
				g.drawLine(tickX, xAxisModel.getPixelYButtom(), tickX, xAxisModel.getPixelYTop());
			}
			/* 绘制刻度线 */
			g.setColor(axisColor);
			g.drawLine(tickX, xAxisModel.getPixelYButtom(), tickX,
					xAxisModel.getPixelYButtom() + xAxisModel.getTickLineLength());
			int tickLabelWidth = g.getFontMetrics().stringWidth(xAxisModel.getTickView(i));
			int tickLabelHeight = g.getFontMetrics().getHeight();
			// 画刻度显示
			g.drawString(xAxisModel.getTickView(i), tickX - (tickLabelWidth / 2), xAxisModel.getPixelYButtom()
					+ tickLabelHeight);
		}
	}
}
